package com._520it.crm.web.controller;

import com._520it.crm.domain.Client;
import com._520it.crm.domain.Employee;
import com._520it.crm.page.AjaxResult;
import com._520it.crm.page.PageResult;
import com._520it.crm.query.ClientQueryObject;
import com._520it.crm.service.IClientService;
import com._520it.crm.service.IEmployeeService;
import com._520it.crm.util.PermissionName;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/client")
public class ClientController {
    @Autowired
    private IClientService clientService;
    @Autowired
    private IEmployeeService employeeService;

    @RequiresPermissions("client:index")
    @PermissionName("客户列表")
    @RequestMapping("")
    public String index() {
        return "client";
    }

    @RequiresPermissions("client:list")
    @PermissionName("客户数据")
    @RequestMapping("/list")
    @ResponseBody
    public PageResult list(ClientQueryObject qo) {
        PageResult pageResult = null;
        pageResult = clientService.queryPage(qo);
        return pageResult;
    }

    @RequiresPermissions("client:selectPotentialClient")
    @PermissionName("查询所有潜在客户")
    @RequestMapping("/selectPotentialClient")
    @ResponseBody
    public List<Client> selectPotentialClient() {
        List<Client> clients = clientService.selectPotentialClient();
        return clients;
    }

    @RequiresPermissions("client:save")
    @PermissionName("客户保存")
    @RequestMapping("/save")
    @ResponseBody
    public AjaxResult save(Client client) {
        AjaxResult result = null;
        try {
            clientService.insert(client);
            result = new AjaxResult(true, "保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("保存失败,请联系管理员！");
        }
        return result;
    }

    @RequiresPermissions("client:update")
    @PermissionName("客户更新")
    @RequestMapping("/update")
    @ResponseBody
    public AjaxResult update(Client client) {
        AjaxResult result = null;
        try {
            clientService.updateByPrimaryKey(client);
            result = new AjaxResult(true, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("更新失败,请联系管理员！");
        }
        return result;
    }

    @RequiresPermissions("client:delete")
    @PermissionName("客户删除")
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult delete(Long clientId) {
        AjaxResult result = null;
        try {
            clientService.deleteByPrimaryKey(clientId);
            result = new AjaxResult(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("删除失败,请联系管理员！");
        }
        return result;
    }

    @RequiresPermissions("client:invalid")
    @PermissionName("客户无效")
    @RequestMapping("/invalid")
    @ResponseBody
    public AjaxResult invalid(Long clientId) {
        AjaxResult result = null;
        try {
            clientService.invalidByPrimaryKey(clientId);
            result = new AjaxResult(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("操作失败,请联系管理员！");
        }
        return result;
    }

    @RequiresPermissions("client:formal")
    @PermissionName("客户转正")
    @RequestMapping("/formal")
    @ResponseBody
    public AjaxResult formal(Long clientId) {
        AjaxResult result = null;
        try {
            clientService.formalByPrimaryKey(clientId);
            result = new AjaxResult(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("操作失败,请联系管理员！");
        }
        return result;
    }

    @RequiresPermissions("client:putPool")
    @PermissionName("客户转正")
    @RequestMapping("/putPool")
    @ResponseBody
    public AjaxResult putPool(Long clientId) {
        AjaxResult result = null;
        try {
            clientService.putPoolByPrimaryKey(clientId);
            result = new AjaxResult(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("操作失败,请联系管理员！");
        }
        return result;
    }

    @RequiresPermissions("client:downloadExcel")
    @PermissionName("Excel导出")
    @RequestMapping("/downloadExcel")
    @ResponseBody
    public void downloadExcel(HttpServletResponse response) {
        try {
            //设置下载头
            String filename = new String("客户数据.xls".getBytes("utf-8"), "iso8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            //查询所有客户
            List<Client> clients = clientService.selectAll();
            //创建一个表格
            Workbook workbook = new HSSFWorkbook();
            //创建工作本
            Sheet sheet = workbook.createSheet();
            //输出一行
            Row row = sheet.createRow(0);
            row.createCell(0).setCellValue("客户编号");
            row.createCell(1).setCellValue("用户名");
            row.createCell(2).setCellValue("客户类型");
            row.createCell(3).setCellValue("状态");
            row.createCell(4).setCellValue("真实姓名");
            row.createCell(5).setCellValue("证件类型");
            row.createCell(6).setCellValue("证件号码");
            row.createCell(7).setCellValue("性别");
            row.createCell(8).setCellValue("电话号码");
            row.createCell(9).setCellValue("邮箱");
            row.createCell(10).setCellValue("地址");
            row.createCell(11).setCellValue("是否投保人");
            row.createCell(12).setCellValue("录入时间");
            row.createCell(13).setCellValue("客户来源");
            row.createCell(14).setCellValue("客户等级");
            row.createCell(15).setCellValue("备注");
            row.createCell(16).setCellValue("录入人");
            row.createCell(17).setCellValue("负责人");
            row.createCell(18).setCellValue("共享人");
            Row clientRow = null;
            Employee inputor = null;
            Employee manager = null;
            Employee sharer = null;
            String sinputtime = null;
            for (int i = 0; i < clients.size(); i++) {
                clientRow = sheet.createRow(i + 1);
                clientRow.createCell(0).setCellValue(clients.get(i).getClientsn() + "");
                clientRow.createCell(1).setCellValue(clients.get(i).getUsername());
                Integer clienttype = clients.get(i).getClienttype();
                if (clienttype != null) {
                    clientRow.createCell(2).setCellValue(clienttype);
                }
                Integer status = clients.get(i).getStatus();
                if (status != null) {
                    clientRow.createCell(3).setCellValue(status);
                }
                clientRow.createCell(4).setCellValue(clients.get(i).getRealname());
                clientRow.createCell(5).setCellValue(clients.get(i).getIdcardtype());
                clientRow.createCell(6).setCellValue(clients.get(i).getIdcardnumber());
                Integer gender = clients.get(i).getGender();
                if (gender != null) {
                    clientRow.createCell(7).setCellValue(gender);
                }
                clientRow.createCell(8).setCellValue(clients.get(i).getPhonenumber());
                clientRow.createCell(9).setCellValue(clients.get(i).getEmail());
                clientRow.createCell(10).setCellValue(clients.get(i).getAddress());
                Integer applicant = clients.get(i).getApplicant();
                if (applicant != null) {
                    clientRow.createCell(11).setCellValue(applicant);
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date inputtime = clients.get(i).getInputtime();
                if (inputtime != null) {
                    sinputtime = format.format(inputtime);
                    clientRow.createCell(12).setCellValue(sinputtime);
                }
                //clientRow.createCell(12).setCellValue(clients.get(i).getInputtime()+"");
                clientRow.createCell(13).setCellValue(clients.get(i).getOrigin());
                Integer clientlevel = clients.get(i).getClientlevel();
                if (clientlevel != null) {
                    clientRow.createCell(14).setCellValue(clientlevel);
                }
                clientRow.createCell(15).setCellValue(clients.get(i).getRemark());
                inputor = clients.get(i).getInputor();
                if (inputor != null) {
                    clientRow.createCell(16).setCellValue(inputor.getRealname());
                }
                manager = clients.get(i).getManager();
                if (manager != null) {
                    clientRow.createCell(17).setCellValue(manager.getRealname());
                }
                sharer = clients.get(i).getSharer();
                if (sharer != null) {
                    clientRow.createCell(18).setCellValue(sharer.getRealname());
                }
            }
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequiresPermissions("client:downloadTemplate")
    @PermissionName("下载客户excel模板")
    @RequestMapping("/downloadTemplate")
    @ResponseBody
    public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
        //设置下载头
        FileInputStream is = null;
        String filename = null;
        try {
            filename = new String("客户数据模板.xls".getBytes("utf-8"), "iso8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            is = new FileInputStream(request.getSession().getServletContext().getRealPath("/static/excelTemplate/客户数据模板.xls"));
            IOUtils.copy(is, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequiresPermissions("client:uploadExcelFile")
    @PermissionName("导入excel")
    @RequestMapping("/uploadExcelFile")
    @ResponseBody
    public AjaxResult uploadExcelFile(MultipartFile excel) {
        AjaxResult result = null;
        try {
            //根据上传的文件,创建一个表
            Workbook workbook = new HSSFWorkbook(excel.getInputStream());
            //获取一个sheet
            Sheet sheet = workbook.getSheetAt(0);
            //获取最后一行
            int lastRowNum = sheet.getLastRowNum();
            Row clientRow = null;
            Client client = null;
            Date date = null;
            SimpleDateFormat simpleDateFormat = null;
            Employee employee1 = null;
            Employee employee2 = null;
            Employee employee3 = null;
            for (int i = 1; i < lastRowNum; i++) {
                clientRow = sheet.getRow(i);
                if (clientRow == null) {
                    break;
                }
                client = new Client();
                String clientsn = (String) getCellValue(clientRow.getCell(0));
                if (clientsn != null) {
                    Long aLong = new Long(clientsn);
                    client.setClientsn(aLong);
                }
                client.setUsername((String) getCellValue(clientRow.getCell(1)));


                Double clienttype = (Double) getCellValue(clientRow.getCell(2));
                if (clienttype != null) {
                    client.setClienttype(clienttype.intValue());
                }
                Double status = (Double) getCellValue(clientRow.getCell(3));
                if (status != null) {
                    client.setStatus(status.intValue());
                }
                client.setRealname((String) getCellValue(clientRow.getCell(4)));
                client.setIdcardtype((String) getCellValue(clientRow.getCell(5)));
                client.setIdcardnumber((String) getCellValue(clientRow.getCell(6)));
                Double gender = (Double) getCellValue(clientRow.getCell(7));
                if (gender != null) {
                    client.setGender(gender.intValue());
                }

                Object phonenumber = getCellValue(clientRow.getCell(8));
                if (phonenumber != null) {
                    client.setPhonenumber(phonenumber.toString());
                }
                client.setEmail((String) getCellValue(clientRow.getCell(9)));
                client.setAddress((String) getCellValue(clientRow.getCell(10)));
                Double applicant = (Double) getCellValue(clientRow.getCell(11));
                if (applicant != null) {
                    client.setApplicant(applicant.intValue());
                }

                Object obj = getCellValue(clientRow.getCell(12));
                if (obj instanceof String) {
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    date = simpleDateFormat.parse((String) obj);
                } else if (obj instanceof Date) {
                    date = (Date) getCellValue(clientRow.getCell(12));

                }

                client.setInputtime(date);

                client.setOrigin((String) getCellValue(clientRow.getCell(13)));
                Double clientlevel = (Double) getCellValue(clientRow.getCell(14));
                if (clientlevel != null) {
                    client.setClientlevel(clientlevel.intValue());
                }

                client.setRemark((String) getCellValue(clientRow.getCell(15)));


                employee1 = employeeService.queryByRealname((String) getCellValue(clientRow.getCell(16)));
                employee2 = employeeService.queryByRealname((String) getCellValue(clientRow.getCell(17)));
                employee3 = employeeService.queryByRealname((String) getCellValue(clientRow.getCell(18)));
                client.setInputor(employee1);
                client.setManager(employee2);
                client.setSharer(employee3);
                clientService.insertByExcelUpload(client);
            }
            result = new AjaxResult(true, "导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("导入失败,请联系管理员！");
        }
        return result;
    }

    @RequestMapping("clientAdd")
    public String clientAdd() {
        return "clientAdd";
    }

    //获取导入数据的真实类型的值
    private Object getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                return cell.getRichStringCellValue().getString();
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue();
                } else {
                    return cell.getNumericCellValue();
                }
            case Cell.CELL_TYPE_BOOLEAN:
                return cell.getBooleanCellValue();
            case Cell.CELL_TYPE_FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }

    @RequestMapping("selectByOrderBillId")
    @ResponseBody
    public Client selectByOrderBillId(Long orderBillId) {
        Client client = null;
        client = clientService.selectByOrderBillId(orderBillId);
        return client;
    }


    @RequestMapping("/riviseClient")
    @ResponseBody
    public AjaxResult rivise(Client client) {
        AjaxResult result = null;
        try {
            clientService.updateFromRivise(client);
            result = new AjaxResult(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("操作失败,请联系管理员！");
        }
        return result;
    }

    @RequestMapping("queryByidcardnumber")
    @ResponseBody
    public Client queryByidcardnumber(String idcardnumber) {
        Client client = null;
        try {
            client = clientService.queryByidcardnumber(idcardnumber);
            if (client == null) {
                client = new Client();
                client.setId(-1L);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    @RequestMapping("alter1")
    @ResponseBody
    public AjaxResult alter1(Client client){
        AjaxResult result = null;
        try {
            clientService.updateClient(client);
            result = new AjaxResult(true,"保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult("保存失败");
        }
        return result;
    }

}
